/**
 * 批量重命名文件
 */

var fs = require('fs'),
    path = require('path');

var dir = process.argv[2] || 'D:/梦瑶视频';

if (!fs.existsSync(dir)) {
    console.log('目录 ' + dir, ' 不存在');
    return;
}
console.log('处理目录 ' + dir);

// 读取并缓存文件参数
var statCache = {};

function getStat(file) {
    var stat = statCache[file];
    if (stat == undefined) {
        stat = fs.statSync(file);
        statCache[file] = stat;
    }
    return stat;
}

// 过滤掉文件夹
function listFiles(dir) {
    var _files = [],
        ff = fs.readdirSync(dir);
    for (i in ff) {
        if (!getStat(path.join(dir, ff[i])).isDirectory()) {
            _files.push(ff[i]);
        }
    }
    return _files;
}

var files = listFiles(dir);

// 按修改日期排序
var i = files.length;
while (i > 0) {
    for (var j = 0; j < i - 1; j++) {
        if (new Date(getStat(path.join(dir, files[j])).mtime).getTime() > new Date(getStat(path.join(dir, files[j + 1])).mtime).getTime()) {
            var temp = files[j];
            files[j] = files[j + 1];
            files[j + 1] = temp;
        }
    }
    i--;
}

// 重命名
var leng = ('' + files.length).length;
for (i in files) {
    var name = ('000000' + ++i).slice(-1 * leng);
    var ext = path.extname(path.join(dir, files[--i]));
    if (!fs.existsSync(path.join(dir, files[i]))) {
        console.log(files[i] + '\t=>\t' + name + ' 1' + ext);
        fs.renameSync(path.join(dir, files[i]), path.join(dir, name + '1' + ext));
    } else {
        console.log(files[i] + '\t=>\t' + name + ext);
        fs.renameSync(path.join(dir, files[i]), path.join(dir, name + ext));
    }
}
